<template>
    <div class="system-role-container layout-padding">
      <div class="system-role-padding layout-padding-auto layout-padding-view">
        <div class="m-header">
          <div class="pro-name">
            <el-input
              clearable
              size="small"
              placeholder="请输入问题描述关键字"
              v-model="proName"
              :suffix-icon="Search"
            />
          </div>

          <div style="display: flex;align-items: center;">
            <!-- <el-button
              size="small"
              @click='exportExcel()'
              :icon="Upload"
              type="success"
              >导出
              </el-button> -->
            <el-button
              size="small"
              @click="newPerson"
              :icon="CirclePlus"
              type="primary"
              >新增记录
              </el-button>
          </div>
        </div>
  
        <div class="table_content">
          <el-table
           @selection-change="handleSelection"
            ref="table_s_exp"
            :height="activeHeight"
            style="width: 100%"
            :header-cell-style="{ background: '#fafbfc', color: '#333333' }"
            :data="tableDataPro"
          >
          
            <el-table-column
              
              
              type="index"
              width="70"
              label="序号"
              align="center"
            />
            <el-table-column
               
              show-overflow-tooltip
              label="问题类型"
                align="left"
              prop="question_type"
            >
            <template  #header>
            <div style="display: flex; align-items: center">
              <div style="margin-right: 5px">问题类型</div>
              <el-popover :width="200" trigger="hover">
                <template #reference>
                  <div
                    class="icone"
                    :class="question_type_s.length == 0 ? '' : 'active'"
                  >
                    <el-icon>
                      <Filter />
                    </el-icon>
                  </div>
                </template>
                <el-select-v2
                 
                  :teleported="false"
                  size="small"
                  style="width: 180px; margin-right: 10px; z-index: 2000"
                  clearable
                  filterable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :options="[
                {
                    value: '图样',
                    label: '图样',
                  },
                  {
                    value: '材料',
                    label: '材料',
                  },
                  {
                    value: '结构',
                    label: '结构',
                  },
                  {
                    value: '技术要求',
                    label: '技术要求',
                  },
                  {
                    label: '计算',
                    value: '计算',
                  },
                  {
                    label: '管理',
                    value: '管理',
                  }
              ]"
                  v-model="question_type_s"
                  placeholder="请输入"
                >
                </el-select-v2>
              </el-popover>
            </div>
          </template>
          
          </el-table-column>

            <el-table-column
            sortable
                 width="400"
              show-overflow-tooltip
              label="问题描述"
              prop="question_desc"
            ></el-table-column>
         

            <el-table-column
            sortable
              width="400"
             show-overflow-tooltip
             label="规范条文或解释"
             prop="standard_explanation"
           ></el-table-column>



           <el-table-column
 
             show-overflow-tooltip
             label="错误类别"
             prop="error_type"
           >
           <template  #header>
            <div style="display: flex; align-items: center">
              <div style="margin-right: 5px">错误类别</div>
              <el-popover :width="200" trigger="hover">
                <template #reference>
                  <div
                    class="icone"
                    :class="error_type_s.length == 0 ? '' : 'active'"
                  >
                    <el-icon>
                      <Filter />
                    </el-icon>
                  </div>
                </template>
                <el-select-v2
                 
                  :teleported="false"
                  size="small"
                  style="width: 180px; margin-right: 10px; z-index: 2000"
                  clearable
                  filterable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :options="[
                {
                    value: '技术性错误',
                    label: '技术性错误',
                  },
                  {
                    value: '一般性错误',
                    label: '一般性错误',
                  },
                  {
                    value: '图面错误',
                    label: '图面错误',
                  },
              ]"
                  v-model="error_type_s"
                  placeholder="请输入"
                >
                </el-select-v2>
              </el-popover>
            </div>
          </template>
          </el-table-column>



            <el-table-column
            sortable
              width="90"
             show-overflow-tooltip
             label="抽查人"
             prop="modify_user"
           ></el-table-column>
          
           <el-table-column
           sortable
              width="140"
             show-overflow-tooltip
             label="抽查时间"
             prop="create_time"
           ></el-table-column>

        <el-table-column fixed="right" label="操作" align="center">
        <template #default="{ row }">
          
          <el-button
           link
            type="primary"
            size="small"
            @click="editTable(row)"
            >编辑</el-button
          >

          <el-popconfirm
            placement="left"
            @confirm="deleteRow(row)"
            title="确认删除?"
          >
            <template #reference>
              <el-button link type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
          
          </el-table>
        </div>
      </div>
  
     
      <el-dialog
      draggable
      @close="closeFrom(RefEdit)"
      title="编辑信息"
      v-model="editDio"
      width="28%"
    >
      <el-form
         label-position="top"
        ref="RefEdit"
        size="small"
        :model="editData"
        :rules="RulesEdit"
        label-width="100px"
      >
      <el-form-item class="my_item" label="问题类型" prop="question_type">
            
          <el-select
          style="width:100%"
            size="small"
            v-model="editData.question_type"
            placeholder="请选择问题类型"
          >
            <el-option
              v-for="item in [
                {
                    value: '图样',
                    label: '图样',
                  },
                  {
                    value: '材料',
                    label: '材料',
                  },
                  {
                    value: '结构',
                    label: '结构',
                  },
                  {
                    value: '技术要求',
                    label: '技术要求',
                  },
                  {
                    label: '计算',
                    value: '计算',
                  },
                  {
                    label: '管理',
                    value: '管理',
                  }
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="my_item" label="问题描述" prop="question_desc">
            <el-input
            resize="none"
             :rows="5"
              type="textarea"
            size="small"
           v-model="editData.question_desc"
            placeholder="请输入问题描述"
          />
        </el-form-item>
        <el-form-item class="my_item" label="规范条文或解释" prop="standard_explanation">
          <el-input
          resize="none"
             :rows="5"
              type="textarea"
            size="small"
         v-model="editData.standard_explanation"
            placeholder="请输入"
          />
        </el-form-item>



        <el-form-item class="my_item" label="错误类别" prop="error_type">
            <el-select
             style="width:100%"
            size="small"
            v-model="editData.error_type"
            placeholder="请选择错误类别"
          >
            <el-option
              v-for="item in [
                {
                    value: '技术性错误',
                    label: '技术性错误',
                  },
                  {
                    value: '一般性错误',
                    label: '一般性错误',
                  },
                  {
                    value: '图面错误',
                    label: '图面错误',
                  },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

     

        <el-form-item class="my_item" label="备注" prop="note">
          <el-input
          resize="none"
             :rows="5"
              type="textarea"
            size="small"
         v-model="editData.note"
            placeholder="请输入备注"
          />
        </el-form-item>
      


        <el-form-item>
            
          <div style="width: 100%; display: flex; flex-direction: row-reverse">
            <el-button @click="editDio = false">取 消</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <el-button
              type="primary"
              @click="handleCopyEquipEdit(RefEdit)"
              >确 定</el-button
            >
          </div>
        </el-form-item>
 
      </el-form>
    </el-dialog>

    
    <el-dialog
      draggable
      @close="addcCloseFrom(RefAdd)"
      title="新增记录"
      v-model="addDio"
      width="28%"
    >
      <el-form
      label-position="top"
        ref="RefAdd"
        size="small"
        :model="addData"
        :rules="RulesEdit"
        label-width="100px"
      >
    
        <el-form-item class="my_item" label="问题类型" prop="question_type">
            <el-select
            style="width:100%"
            size="small"
            v-model="addData.question_type"
            placeholder="请选择问题类型"
          >
            <el-option
              v-for="item in [
                {
                    value: '图样',
                    label: '图样',
                  },
                  {
                    value: '材料',
                    label: '材料',
                  },
                  {
                    value: '结构',
                    label: '结构',
                  },
                  {
                    value: '技术要求',
                    label: '技术要求',
                  },
                  {
                    label: '计算',
                    value: '计算',
                  },
                  {
                    label: '管理',
                    value: '管理',
                  }
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="my_item" label="问题描述" prop="question_desc">
            <el-input
            resize="none"
             :rows="5"
              type="textarea"
            size="small"
           v-model="addData.question_desc"
            placeholder="请输入问题描述"
          />
        </el-form-item>
        <el-form-item class="my_item" label="规范条文或解释" prop="standard_explanation">
          <el-input
          resize="none"
             :rows="5"
              type="textarea"
            size="small"
         v-model="addData.standard_explanation"
            placeholder="请输入"
          />
        </el-form-item>


        <el-form-item class="my_item" label="错误类别" prop="error_type">
            <el-select
              style="width:100%"
            size="small"
            v-model="addData.error_type"
            placeholder="请选择错误类别"
          >
            <el-option
              v-for="item in [
                {
                    value: '技术性错误',
                    label: '技术性错误',
                  },
                  {
                    value: '一般性错误',
                    label: '一般性错误',
                  },
                  {
                    value: '图面错误',
                    label: '图面错误',
                  },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>


     

        <el-form-item class="my_item" label="备注" prop="note">
          <el-input
          resize="none"
             :rows="5"
              type="textarea"
            size="small"
         v-model="addData.note"
            placeholder="请输入"
          />
        </el-form-item>
      


        <el-form-item>
       
          <div style="width: 100%; display: flex; flex-direction: row-reverse">
            <el-button @click="addDio = false">取 消</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <el-button
          
              type="primary"
              @click="handleCopyAdd(RefAdd)"
              >确 定</el-button
            >
          </div>
        </el-form-item>
 
      </el-form>
    </el-dialog>




    </div>

  </template>
    
    <script setup name="systemRole">
    import JSZipUtils from "jszip-utils";
import docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";
import JSZip from "pizzip";
import ImageModule from 'docxtemplater-image-module-free'
  import { onMounted, ref, watch } from "vue";
  import { ElMessageBox, ElMessage } from "element-plus";
  import {
    Close,
    Search,
    PictureFilled,
   
    CirclePlus,
    Upload,
    Download,
    Delete,
    Filter,
    Warning
  } from "@element-plus/icons-vue";
  import { useProjectStore } from "../../stores/project";
  import { storeToRefs } from "pinia";
  import {
    DeleteDesignOptimizationScheme,
    GetDesignOptimizationSchemes,
    AddUpdateDesignOptimizationScheme,
   
  } from "../../api/dept";
  import PinYinMatch from "pinyin-match";
  import {DeleteDesignFileCheckProblemRecord,AddOrUpdateDesignFileCheckProblemRecord,GetDesignFileCheckProblemRecord} from '../../api/technicalManagement'
  let store = useProjectStore();
  
  let list_filtered = ref([]);
  
  
  let { projectInfo } = storeToRefs(store);
  
  let proName = ref("");
  let sex_ = ref([])
  watch(proName, async () => {
    if (proName.value) {
      let res = await GetDesignFileCheckProblemRecord();
     
      let data = JSON.parse(JSON.stringify(res));
      tableDataPro.value = data
        .filter(
          (v) =>
            v.question_desc.includes(proName.value)
        )
       
    } else {
      getProTable(
        {},
        question_type_s.value,
        error_type_s.value,
     
       
      );
    }
  });





let del_item = (item) => {
    fileBase64Str.value  = fileBase64Str.value.filter(v=>!(v == item))
}

let del_item_change = (item) => {

    if(fileBase64Str.value.length == 1){
        editData.value.attached_schedule = ''
    }
    fileBase64Str.value  = fileBase64Str.value.filter(v=>!(v == item))
}







  
  let matchProfessional = (searchContent) => {
    if (searchContent) {
      let result = [];
      professional_leader_data_options.value.forEach((item) => {
        // matchResult 的值为 true/false
        let matchResult = PinYinMatch.match(item.label, searchContent);
        if (matchResult) {
          result.push(item);
        }
      });
   
      professional_leader_data_options_PY.value = result;
    } else {
      professional_leader_data_options_PY.value = professional_leader_data_options.value;
    }
  };

  



  let matchTeamLeader = (searchContent) => {
    if (searchContent) {
      let result = [];
      team_leader_options.value.forEach((item) => {
        // matchResult 的值为 true/false
        let matchResult = PinYinMatch.match(item.label, searchContent);
        if (matchResult) {
          result.push(item);
        }
      });
  
      team_leader_options_PY.value = result;
    } else {
      team_leader_options_PY.value = team_leader_options.value;
    }
  };

   let RefEdit = ref(null)
  let  closeFrom = () => {
   
    RefEdit.value.resetFields();
  }

  let handleCopyEquipEdit = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      
        await AddOrUpdateDesignFileCheckProblemRecord({
        ...editData.value,
        modify_user:JSON.parse(localStorage.getItem("userMessage")).user_name,
       })

      ElMessage({
        message: "修改成功",
        type: "success",
      });
      editDio.value = false;
      getProTable(
        {},
        question_type_s.value,
        error_type_s.value,
     
       
      );
    }
  });
};



let exportExcel = () => {

  let obj = {
    table:exportData.value.map((v,i)=>{
      return{
        index: i + +1,
        optimal_classification:v.optimal_classification,
        unit_classification:v.unit_classification,
        design_habits_practices:v.design_habits_practices,
        improvement_measure:v.improvement_measure,
        hasImage:(v.attached_schedule.includes('base64'))? false: true,
        attached_schedule_str:(!(v.attached_schedule.includes('base64'))?v.attached_schedule : null),
        attached_schedule_img:((v.attached_schedule.includes('base64'))? (
          v.attached_schedule.split('||').map(v=>{
             return {
               imgUrl:v
             }
           })
        ): null),
        note:v.note
      } 
    })
  }


  exportWordDocx({name:'设备专业设计优化方案库',data:obj})
}


let exportWordDocx  = ({name, data : wordData}) => {
   
   const url = `/${name}.docx`;
   JSZipUtils.getBinaryContent(url,(err, data)=>{
     if (err) {
     ElMessage.error("导出报告出错");
     console.log("err:", err);
     return;
   }
   let zip = new JSZip(data);
   const Docxtemplater = docxtemplater;
   const imageOptions = {
     centered: false,
     getImage(tagValue, tagName) {
       return new Promise(function (resolve, reject) {
         JSZipUtils.getBinaryContent(tagValue, function (error, content) {
           if (error) {
             return reject(error);
           }
           return resolve(content);
         });
       });
     },
     getSize(img, tagValue, tagName) {
       // 非固定大小（这里是设置宽度最大为500px的图片）
       return new Promise(function (resolve, reject) {
         let image = new Image();
         image.src = tagValue;
         let imgWidth, imgHeight;
         image.onload = function () {
          
          imgWidth = 110
           imgHeight = (image.height * imgWidth )  / image.width;
          
           resolve([imgWidth, imgHeight]);
         };
         image.onerror = function (e) {
           console.log("img, tagValue, tagName : ", img, tagValue, tagName);
           reject(e);
         };
       });
     },
   };


   const nullGetter = (part, scopeManager) => {
     if (!part.module) {
       return "";
     }
   };
   let doc = new Docxtemplater(zip, {linebreaks: true,  nullGetter: nullGetter, modules: [new ImageModule(imageOptions)] });
  
   doc.resolveData({...wordData}).then(()=>{
     doc.render();
     let out = doc.getZip().generate({
       type: "blob",
       MimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
     });
     saveAs(out, `${name}.docx`);
   })
 })
 }





let handleCopyAdd = (formEl) => {
    if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
        
        
       await AddOrUpdateDesignFileCheckProblemRecord({
        ...addData.value,
        create_user:JSON.parse(localStorage.getItem("userMessage")).user_name,
        modify_user:JSON.parse(localStorage.getItem("userMessage")).user_name,
       })
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      addDio.value = false;
      getProTable(
        {},
        question_type_s.value,
        error_type_s.value,
     
       
      );
    }
  });


}

let RefAdd =ref(null)
let addDio = ref(false)
let addData = ref({})
let editDio = ref(false)
let editData = ref({})
let RulesEdit = ref({
    question_type: [{ required: true, message: '请选择', trigger: 'change' }],
    question_desc: [{ required: true, message: '请输入', trigger: 'blur' }],
    error_type: [{ required: true, message: '请选择', trigger: 'change' }], 
    standard_explanation:[{ required: true, message: '请输入', trigger: 'blur' }],
    note: [{ required: false, message: '请输入', trigger: 'blur' }], 
})
  let editTable = (data) => {
    
    editData.value = {...data}

    editDio.value = true


  }



  let deleteRow = async(data) => {
    await DeleteDesignFileCheckProblemRecord({id:data.id})
    getProTable(
        {},
        question_type_s.value,
        error_type_s.value,
     
       
      );
   ElMessage.success('删除成功')

  }


  let question_type_s = ref([])
  let error_type_s = ref([])

let exportData = ref([])

  let handleSelection = (val) => {
    exportData.value = val
  }


  let addcCloseFrom = () => {
   
    RefAdd.value.resetFields()
  }

  let newPerson = () => {
    addDio.value = true
  }


  let proj_name_data = ref([])
  let proj_name_data_options = ref([])
  let professional_leader_data = ref([])
  let professional_leader_data_options = ref([])
  let professional_leader_data_options_PY = ref([])
  let team_leader_data = ref([])
  let team_leader_options = ref([])
  let team_leader_options_PY  = ref([])
  
  let work_major_ = ref([])
  let educational_ = ref([])
  let professional_post_ = ref([])
  let design_post_= ref([])
  let qualification_ =ref([])

  let calculateAge = (birthday) => {
  // 创建一个日期对象，表示出生日期
  const birthDate = new Date(birthday);

  // 创建一个日期对象，表示当前日期
  const today = new Date();

  // 计算年份差
  let age = today.getFullYear() - birthDate.getFullYear();

  // 如果生日还没到，年龄减1
  if (today.getMonth() < birthDate.getMonth() || 
      (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())) {
    age--;
  }

  return age;
}

  let getProTable = async (data,question_type=[],error_type=[]) => {
    let res = await GetDesignFileCheckProblemRecord();
 
    let ORGdata = JSON.parse(JSON.stringify(res));
   
    const filters = {
        question_type, 
        error_type,
 
    };
  
    
    tableDataPro.value = multiFilter(JSON.parse(JSON.stringify(ORGdata)), filters)
  
  };
  
  function multiFilter(array, filters) {
    const filterKeys = Object.keys(filters);
  
    return array.filter((item) => {
      return filterKeys.every((key) => {
        
 if (!filters[key].length) return true;
        return !!~filters[key].indexOf(item[key]);
      });
    });
  }
  
  let getOptionsData = (data, str) => {
    return [...new Set(data.map((v) => v[str]))]
      .filter((v) => {
        if (v) {
          return v;
        }
      })
      .map((v) => {
        return {
          value: v,
          label: v,
        };
      });
  };
  
  
  watch([error_type_s,question_type_s],()=>{
    getProTable(
        {},
        question_type_s.value,
        error_type_s.value,
     
       
      );
  })
  
  
  let personOptions = ref([]);
  
  
  
  
  let tableDataPro = ref([]);
  
  
  

  
  
  
  watch(
    projectInfo,
    () => {
      if (projectInfo.value && Object.keys(projectInfo.value).length > 0) {
        
        getProTable(
        {},
        question_type_s.value,
        error_type_s.value,
     
       
      );
      }
    },
    { immediate: true }
  );
  
  
  
  
  let activeHeight = ref(0);
  
  
  let userOptionsleader = ref([]);
  let optionsNewteam_leader = ref([]);
  
  
  // 页面加载时
  onMounted(() => {
    activeHeight.value =
      document.querySelector(".system-role-padding").clientHeight - 80;
    window.addEventListener("resize", () => {
      activeHeight.value =
        document.querySelector(".system-role-padding").clientHeight - 80;
    });
  });
  </script>
    
    <style scoped lang="scss">
  .m-header {
    display: flex;
    align-items: center;
  }
  .m-header .pro-name {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  .m-header .el-input {
    width: 300px;
  }
  .m-header .el-button {
    margin-right: 10px;
  }
  
  .system-role-container {
    .system-role-padding {
      padding: 15px;
      .el-table {
        flex: 1;
      }
    }
  }
  .button_footer {
    display: flex;
    flex-direction: row-reverse;
    width: 100%;
  }
  .table_content {
    margin-top: 20px;
  }
  
  ::v-deep(.el-table--large .el-table__cell) {
    padding: 6px 0;
  }
  
  .table_box {
    padding: 20px 50px;
  }
  
  .button_poastion_flex_iem {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
  }
  
  .demo-tabs > .el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
  }
  
  .el-tabs--right .el-tabs__content,
  .el-tabs--left .el-tabs__content {
    height: 100%;
  }
  
  .backgroun_border {
    // 	::v-deep .el-tabs__header {
    //     margin-top: 39px;
    //   }
  }
  
  ::v-deep(.el-tabs__item::after) {
    position: absolute;
    content: " ";
    top: 0;
    width: 2px;
    height: 100%;
    background: #eee;
    right: 0;
  }
  
  
  .active {
    color: rgb(24, 144, 255);
  }
  
  .icone {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  ::v-deep(.cell){
    // display: flex;
    // align-items: center;
  }


  .active {
    color: rgb(24, 144, 255);
  }
  
  .icone {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  </style>
    